<template>
  <PageTemplate title="近期那些事">
    <template #default>
      <scroll-view 
        class="scroll-container" 
        scroll-y="true"
        enable-back-to-top="true"
        @scrolltolower="onScrollToLower"
        @scrolltoupper="onScrollToUpper"
        :refresher-enabled="true"
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
      >
        <view class="scroll-content">
          <!-- 数据列表 -->
          <view class="posts-container">
            <view class="publish-card" v-for="(item, index) in posts" :key="item.publish_id">
              <!-- 卡片头部（用户信息和时间） -->
              <view class="card-header">
                <view class="user-info">
                  <image class="avatar" :src="item.author?.avatar" mode="widthFix" />
                  <view class="user-meta">
                    <text class="user-name">{{ item.author?.name || '匿名用户' }}</text>
                  </view>
                </view>

                <view class="publish-time">
                  <image class="time-icon" src="/static/publish/i-clock.png" mode="aspectFit" />
                  <text>{{ formatDate(item.createdAt) }}</text>
                </view>
              </view>

              <!-- 卡片内容区 -->
              <view class="card-content">
                <!-- 文字内容 -->
                <view class="content-text" v-if="item.content && item.content.trim()">
                  <text>{{ item.content }}</text>
                </view>

                <!-- 图片内容 -->
                <view class="content-imgs" v-if="item.images && item.images.length > 0">
                  <view class="img-grid" :class="getImgClass(item.images.length)">
                    <image
                        class="publish-img"
                        v-for="(img, imgIdx) in item.images"
                        :key="img.upload_id"
                        :src="img.fileurl"
                        mode="widthFix"
                        @click="previewImage(img.fileurl, item.images)"
                        lazy-load
                    />
                  </view>
                </view>
              </view>

              <!-- 互动区域 -->
              <view class="card-actions" v-if="(item.content && item.content.trim()) || (item.images && item.images.length > 0)">
                <view class="action-item" @click="handleLike(item)">
                  <image
                      class="action-icon"
                      :src="item.is_liked ? '/static/publish/i-dianzhan.png' : '/static/publish/i-quxiaodianzan.png'"
                      mode="aspectFit" />
                  <text class="action-text">{{ item.like_count }}</text>
                </view>
                <view class="action-item" @click="focusCommentInput(item)">
                  <image class="action-icon" src="/static/publish/i-pinglun.png" mode="aspectFit" />
                  <text class="action-text">{{ item.comment_count }}</text>
                </view>
              </view>

              <!-- 评论区域 -->
              <view class="comment-area" v-if="item.showComments || (item.comments && item.comments.length > 0)">
                <!-- 评论列表 -->
                <view class="comments-list" v-if="item.comments && item.comments.length > 0">
                  <view class="comment-item" v-for="comment in item.comments" :key="comment.comment_id">
                    <image class="comment-avatar" :src="comment.author.avatar || '/static/default_avatar.png'" mode="aspectFill" />
                    <view class="comment-content">
                      <view class="comment-user">{{ comment.author.name }}</view>
                      <view class="comment-text">{{ comment.content }}</view>
                      <view class="comment-meta">
                        <text class="comment-time">{{ formatDate(comment.createdAt) }}</text>
                        <text class="reply-btn" @click="replyToComment(item, comment)">回复</text>
                      </view>
                    </view>
                  </view>
                </view>
                <!-- 无评论提示 -->
                <view class="no-comments" v-else>
                  <text>暂无评论，快来抢沙发吧~</text>
                </view>

                <!-- 评论输入框 -->
                <view class="comment-input-container">
                  <textarea
                      class="comment-input"
                      placeholder="写评论..."
                      v-model="item.new_comment"
                      :auto-height="true"
                      @confirm="handleComment(item)"
                  />
                  <button class="send-button" @click="handleComment(item)">发送</button>
                </view>
              </view>
            </view>

            <!-- 空数据提示 -->
            <view class="empty-container" v-if="posts.length === 0 && !loading && !refreshing">
              <image class="empty-icon" src="/static/publish/i-meiyoushuju.png" mode="aspectFit" />
              <text class="empty-text">暂无数据</text>
            </view>

            <!-- 加载更多 -->
            <view class="load-more" v-if="loading">
              <image class="loading-icon" src="/static/publish/i-jiazaizhong.png" mode="aspectFit" />
            </view>
            
            <!-- 到底了提示 -->
            <view class="no-more" v-else-if="noMore && posts.length > 0">
              <image class="no-more-icon" src="/static/publish/i-daodile.png" mode="aspectFit" />
            </view>
          </view>
        </view>
      </scroll-view>
    </template>
  </PageTemplate>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getPublishList } from '@/api/publish/index.ts'
import { createLike, deleteLike } from '@/api/publish/like.ts'
import { createComment } from '@/api/publish/comment.ts'
import { formatDate, showToast } from '@/utils/index.ts'
import PageTemplate from '@/components/PageTemplate.vue';

const posts = ref([])
const loading = ref(false)
const noMore = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const refreshing = ref(false) // 下拉刷新状态

// 防重复加载标志
const isLoading = ref(false)

// 预览图片
const previewImage = (currentImage, images) => {
  const urls = images.map(img => img.fileurl)
  uni.previewImage({
    current: currentImage,
    urls: urls
  })
}

// 点赞/取消点赞
const handleLike = async (post) => {
  try {
    if (post.is_liked) {
      // 取消点赞
      const res = await deleteLike({ publish_id: post.publish_id })
      if (res.code === 200) {
        post.like_count--
        post.is_liked = false
      }
    } else {
      // 点赞
      const res = await createLike({ publish_id: post.publish_id })
      if (res.code === 200) {
        post.like_count++
        post.is_liked = true
      }
    }
  } catch (err) {
    console.error('操作失败:', err)
  }
}

// 聚焦评论输入框
const focusCommentInput = (post) => {
  // 实际项目中可能需要滚动到输入框位置
  // 切换评论区域显示状态
  post.showComments = !post.showComments;
}

// 发表评论
const handleComment = async (post) => {
  if (!post.new_comment || post.new_comment.trim() === '') {
    showToast('请输入评论内容')
    return
  }

  try {
    const res = await createComment({
      publish_id: post.publish_id,
      content: post.new_comment
    })

    // 初始化评论数组
    if (!post.comments) {
      post.comments = []
    }

    // 添加新评论到开头
    post.comments.unshift(res.data)
    post.comment_count++
    post.new_comment = '' // 清空输入框

    showToast('评论成功', 'success')
  } catch (err) {
    console.error('评论失败:', err)
  }
}

// 回复评论
const replyToComment = (post, comment) => {
  post.new_comment = `回复${comment.author.name}: `
  post.showComments = true;
  // 实际项目中可能需要记录被回复的评论ID
}

// 获取图片类名
const getImgClass = (length) => {
  if (length === 1) {
    return 'single-image';
  } else if (length > 1) {
    return 'multi-image';
  }
  return '';
}

// 加载帖子列表
const loadPosts = async (page = 1, showLoading = true) => {
  // 防止重复加载
  if (isLoading.value && page > 1) return
  
  // 设置加载状态
  isLoading.value = true
  if (showLoading && page === 1) {
    loading.value = true
  }
  
  try {
    const res = await getPublishList({
      page: page,
      limit: pageSize.value
    })

    const newPosts = res.data.list

    // 处理数据，添加评论和点赞状态字段
    newPosts.forEach(post => {
      post.new_comment = ''
      // 从服务器返回的数据中获取实际的点赞状态
      post.is_liked = post.is_liked || false
      post.showComments = false // 默认不显示评论区域
      // 直接使用后端返回的评论数据
      post.comments = post.comments || []
    })

    if (page === 1) {
      posts.value = newPosts
      // 判断是否还有更多数据
      if (newPosts.length < pageSize.value) {
        noMore.value = true
      } else {
        noMore.value = false // 重置，允许继续加载
      }
    } else {
      posts.value = [...posts.value, ...newPosts]
      // 判断是否还有更多数据
      if (newPosts.length < pageSize.value) {
        noMore.value = true
      }
    }

    currentPage.value = page
  } catch (err) {
    console.error('获取发布内容失败:', err)
  } finally {
    // 重置加载状态
    isLoading.value = false
    loading.value = false
    // 如果是下拉刷新需要停止刷新状态
    if (page === 1) {
      refreshing.value = false
    }
  }
}

// 加载更多
const loadMore = () => {
  if (!loading.value && !noMore.value && !isLoading.value) {
    loadPosts(currentPage.value + 1)
  }
}

// 下拉刷新
const onRefresh = async () => {
  if (refreshing.value) return
  refreshing.value = true
  currentPage.value = 1
  noMore.value = false
  await loadPosts(1, false)
}

// 上拉加载更多
const onScrollToLower = () => {
  if (!loading.value && !noMore.value && !isLoading.value) {
    loadMore()
  }
}

// 下拉到顶部
const onScrollToUpper = () => {
  // 可以在这里处理一些回到顶部的逻辑
}

// 页面显示时重新加载数据，确保获取最新发布的消息
onMounted(() => {
  currentPage.value = 1
  if (!loading.value) {
    loadPosts(1, false) // 不显示加载提示，利用下拉刷新效果
  }
})
</script>

<style scoped>
.scroll-container {
  overflow: auto;
  padding: 0 30rpx;
  height: 100%;
}

.posts-container {
  height: calc(100% - 20rpx);
}

.publish-card {
  background-color: #ffffff;
  margin-bottom: 20rpx;
  padding: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.user-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.publish-time {
  font-size: 24rpx;
  color: #999;
  display: flex;
  align-items: center;
}

.time-icon {
  width: 28rpx;
  height: 28rpx;
  margin-right: 8rpx;
}

.card-content {
  margin-bottom: 20rpx;
}

.content-text {
  font-size: 30rpx;
  line-height: 1.5;
  color: #333;
  margin-bottom: 20rpx;
}

.content-imgs {
  margin-bottom: 20rpx;
}

.img-grid {
  display: grid;
  grid-gap: 10rpx;
}

.single-image {
  width: 100%;
  max-width: 400rpx;
}

.single-image .publish-img {
  width: 100%;
  border-radius: 10rpx;
}

.multi-image {
  grid-template-columns: repeat(3, 1fr);
}

.multi-image .publish-img {
  width: 220rpx;
  height: 220rpx;
  border-radius: 10rpx;
}

.card-actions {
  display: flex;
  border-top: 1rpx solid #f0f0f0;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
}

.action-item {
  display: flex;
  align-items: center;
  margin-right: 40rpx;
}

.action-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 10rpx;
}

.action-text {
  font-size: 28rpx;
  color: #666666;
}

.comment-area {
  background-color: #f8f9fa;
  border-radius: 10rpx;
  padding: 20rpx;
}

.comment-input-container {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  margin-bottom: 10rpx;
  padding: 6rpx;
  background-color: #ffffff;
  border-radius: 36rpx;
  border: 1rpx solid #f0f0f0;
  min-height: 70rpx;
}

.comment-input {
  flex: 1;
  padding: 20rpx;
  font-size: 28rpx;
  background-color: transparent;
  border: none;
  outline: none;
  min-height: 50rpx;
  line-height: 40rpx;
  vertical-align: middle;
  resize: none;
  width: 100%;
}

.send-button {
  font-size: 26rpx;
  padding: 12rpx 24rpx;
  background: linear-gradient(90deg, #ff7e5f, #feb47b);
  color: white;
  border-radius: 30rpx;
  border: none;
  box-shadow: 0 4rpx 10rpx rgba(255, 126, 95, 0.3);
  height: auto;
  line-height: normal;
}

.comments-list {
  max-height: none;
  overflow-y: visible;
}

.comment-item {
  display: flex;
  margin-bottom: 20rpx;
  padding: 10rpx;
  background-color: #ffffff;
  border-radius: 10rpx;
}

.comment-avatar {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  margin-right: 15rpx;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-user {
  font-weight: bold;
  font-size: 26rpx;
  margin-bottom: 5rpx;
  color: #333;
}

.comment-text {
  font-size: 28rpx;
  line-height: 1.4;
  margin-bottom: 5rpx;
  color: #666;
}

.comment-meta {
  display: flex;
  font-size: 24rpx;
  color: #999999;
}

.reply-btn {
  margin-left: 20rpx;
  color: #ff7e5f;
}

.no-comments {
  text-align: center;
  padding: 30rpx;
  font-size: 26rpx;
  color: #999;
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.load-more {
  text-align: center;
  padding: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-icon {
  width: 100rpx;
  height: 100rpx;
}

.no-more {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30rpx 0;
  color: #999;
}

.no-more-icon {
  width: 200rpx;
  height: 100rpx;
  margin-bottom: 10rpx;
}

</style>